/*
 * 地址选择
 */
'use strict';
import React, { Component } from 'react';
import {
    View,
    Text,
    StyleSheet,
    Image,
    ListView,
    RefreshControl,
    ActivityIndicator,
    TouchableOpacity,
    Dimensions,
    Animated,
    TouchableHighlight,
    AsyncStorage,
    PixelRatio,
    TextInput,
    Alert,
    ScrollView
} from 'react-native';

import GridView from 'react-native-gridview';

import Toast from 'antd-mobile/lib/toast';
import List from 'antd-mobile/lib/list';
import Flex from 'antd-mobile/lib/flex';
import Carousel from 'antd-mobile/lib/carousel';

import NavTitle from '../component/NavTitle';

const Item = List.Item;

import XFetch from '../XFetch';

import GoodsDetail from './GoodsDetail';

import ErweimaShop from './ErweimaShop';

import ErweimaPro from './ErweimaPro';

import AddGoods from './AddGoods';

import * as WechatAPI from 'react-native-wx';

import Communications from '../utils/Communications';
import MyWebView from '../utils/MyWebView';

import * as QQAPI from 'react-native-qq';

import Popup from 'antd-mobile/lib/popup';
import Grid from 'antd-mobile/lib/grid';


const itemsPerRow = 2;

var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});

let _loginStauts = false;

class ProductShops extends Component {
    constructor(props) {
        super(props);
        this.state = {
            data:[],
            image:'',
            title:'',
            content:'',
            focuimgs:[],
            datetime:'',
            dataSource: ds.cloneWithRows([]),
            username:'默认用户',
            comment:void 0,
            telphone:'10086',
            text:'http://www.weiweigou.com',
            hits:0,
            lat:void 0,
            lng:void 0,
            isRenZheng:false,
            baoZeng_Money:0
        }

    }

    _getLoginStatus(){
        AsyncStorage.getItem('serveid').then(value=>{
            if(!value){
                _loginStauts = true;
            }
        });
    }


    componentDidMount(){
        this._getLoginStatus();
        AsyncStorage.getItem('username').then(data=>{
            if(data){
                this.setState({
                    username:data
                })
            }
        })
        this._getData();
    }

    _getData(){
        XFetch(`http://www.weiweigo.com/app/shop.aspx?method=showDetail&shopid=${this.props.id}`,{
            method:'GET'
        }).then(data=>{
            this.setState({
                hits:data.hits,
                telphone:data.tel,
                lat:data.lat,
                lng:data.lon,
                image:'http://www.weiweigo.com'+data.imgUrl,
                text:`http://www.weiweigo.com/productlist.aspx?shopid=${data.shopId}&aid=${data.addressId}`,
                content:data.summary,
                datetime:data.datetime,
                isRenZheng:data.isRenZheng,
                baoZeng_Money:data.baoZeng_Money,
                title:data.title,
                focuimgs:[...JSON.parse(data.focusimg),...JSON.parse(data.focusimg)]
            },this._getGoods.bind(this))
        });
    }

    _getGoods(){
        XFetch(`http://www.weiweigo.com/app/goods.aspx?method=listByPage&shopid=${this.props.id}`,{
            method:'GET'
        }).then(data=>{
            this.setState({
                data:data.data
            },this._getcomment.bind(this))
        });
    }
    _getcomment(){
        XFetch(`http://www.weiweigo.com/app/content.aspx?method=commentList&channelid=2&id=${this.props.id}&p=1`,{
            method:'GET',
        }).then(data=>{
            this.setState({
                dataSource:ds.cloneWithRows(data)
            })
        });
    }

    _onShowDatail(data){
        this.props.navigator.push({
            component: GoodsDetail,
            name: 'GoodsDetail',
            params:{
                id:data.id,
                me:this.props.me
            }
        })
    }

    _renderRow(rowData, sectionID, rowID){
        return(
            <View style={styles.evaluateItem}>
                <Text style={styles.evaluateLabel}>{rowData.NAME?rowData.NAME:'默认用户'}</Text>
                <Text style={styles.evaluateContent}>{rowData.COMMENTCON}</Text>
            </View>
        )
    }

    _submit(){
        if(_loginStauts){
            Toast.info('请先登录',2);
            return;
        }
        fetch(`http://www.weiweigo.com/app/content.aspx?method=comment`,{
            method:'POST',
            headers: {
                "Content-Type": "application/x-www-form-urlencoded"
            },
            body:`channelid=2&id=${this.props.id}&plcon=${this.state.comment}`
        }).then(data=>{
            data.json().then(data=>{
                if(data.success){
                    Toast.success('评论成功', 1);
                    this._getcomment();
                }
            });
        });
    }

    _getErweima(){
        this.props.navigator.push({
            name:'ErweimaShop',
            component:ErweimaShop,
            params:{
                id:this.props.id
            }
        })
    }

    _getProErweima(data){
        this.props.navigator.push({
            name:'ErweimaPro',
            component:ErweimaPro,
            params:{
                id:data.id
            }
        })
    }

    _share(){
        WechatAPI.shareToSession({
            type: 'text',
            text: `http://www.weiweigo.com/productlist.aspx?shopid=${this.props.id}&aid=`,
        })
    }

    _navigation(){
        let _pos = '25.049214,102.703629';
        if(this.state.lat){
            _pos = this.state.lat + ','+this.state.lng;
        }
        this.props.navigator.push({
            name:'MyWebView',
            component:MyWebView,
            params:{
                path:`http://apis.map.qq.com/tools/poimarker?type=0&marker=coord:${_pos};title:${this.state.title};&key=55JBZ-6L6KU-5Z6V3-25OQM-CXWJ5-RJFT2&referer=myapp`
            }
        })
    }


    render() {
        return (
            <View style={styles.container}>
                <NavTitle
                    title='店铺详情'
                    headColor = '#fbdc3a'
                    leftButton = {true}
                    leftImg={require('../imgs/left.png')}
                    leftText = {'返回'}
                    leftHander = {()=>{
                        this.props.navigator.pop();
                    }}
                    rightButton={true}
                    rightText = {this.props.me?'添加产品':'分享'}
                    rightHander={()=>{
                        if(this.props.me){
                            this.props.navigator.push({
                                name:'AddGoods',
                                component:AddGoods
                            })
                        }else{
                            Popup.show(
                            <Grid hasLine={false} onClick={(ele,index)=>{
                                if(index === 0){
                                    WechatAPI.shareToSession({
                                        type: 'text',
                                        text: this.state.text
                                    })
                                }else if(index === 1){
                                    WechatAPI.shareToTimeline({
                                        type: 'text',
                                        text: this.state.text
                                    })
                                }else if(index === 2){
                                    QQAPI.shareToQQ({
                                        type: 'news',
                                        title: '微微购',
                                        description: '微微购服务详情分享',
                                        webpageUrl: this.state.text,
                                        imageUrl: 'http://ouxiurkf8.bkt.clouddn.com/2017-08-21_DOtOgI4n.png',
                                    });
                                }else if(index === 3){
                                    QQAPI.shareToQzone({
                                        type: 'news',
                                        title: '微微购',
                                        description: '微微购服务详情分享',
                                        webpageUrl: this.state.text,
                                        imageUrl: 'http://ouxiurkf8.bkt.clouddn.com/2017-08-21_DOtOgI4n.png',
                                    });
                                }
                                Popup.hide();
                            }} data={[{
                                icon: require('../imgs/erweima2.png'),
                                text: `分享好友`,
                            },{
                                icon: require('../imgs/erweima3.png'),
                                text: `分享朋友圈`,
                            },{
                                icon: require('../imgs/erweima5.png'),
                                text: `分享QQ`,
                            },{
                                icon: require('../imgs/erweima6.png'),
                                text: `分享空间`,
                            }]} columnNum={3} renderItem={(ele,index)=>{
                                return (
                                    <View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
                                        <Image source={ele.icon} style={{width:42,height:42}}/>
                                        <Text style={{marginTop:5}}>{ele.text}</Text>
                                    </View>
                                )
                            }}/>
                        ,{animationType: 'slide-up',onMaskClose(){},maskClosable:true});
                        }
                    }}
                />
                <ScrollView
                    showsVerticalScrollIndicator={false}
                >
                    <View style={{height:100}}>
                        <Carousel
                            autoplay={true}
                            infinite
                            dots = {false}
                        >
                            {this.state.focuimgs.map((ii,index) => (
                                <Image
                                    key={`slideriiiImg${index}`}
                                    source={{uri:`http://www.weiweigo.com${ii.src}`}}
                                    style={styles.sliderImage}
                                    resizeMode="stretch"
                                />
                            ))}
                        </Carousel>
                    </View>
                    <View style={styles.content}>
                        <View style={styles.head}>
                            <Text style={styles.title}>{this.state.title}</Text>
                            <Text style={styles.scanCount}>浏览次数:{this.state.hits}</Text>
                        </View>
                        <View style={styles.service}>
                            <Text style={styles.serviceDetail}>发布时间:{this.state.datetime.split(' ')[0]}</Text>
                            <Text
                                numberOfLines={2}
                                style={styles.serviceDetail}
                            >
                                {/\n/g.test(this.state.content)?this.state.content.replace(/\n/,''):this.state.content}
                            </Text>
                        </View>
                        <View style={styles.tabIcon}>
                            <View style={[styles.tabClick,{marginLeft:0}]}>
                                <Image style={[styles.tabImg,{width:22}]} source={this.state.isRenZheng?require('../imgs/select.png'):require('../imgs/selectNo.png')}></Image>
                                <Text style={styles.tabText}>资历认证</Text>
                            </View>
                            <View style={styles.tabClick}>
                                <Image style={styles.tabImg} source={this.state.baoZeng_Money != 0?require('../imgs/select.png'):require('../imgs/selectNo.png')}></Image>
                                <Text style={styles.tabText}>保证金</Text>
                            </View>
                            <TouchableOpacity style={styles.tabClick} onPress={this._getErweima.bind(this)}>
                                <Image style={styles.tabImg} source={require('../imgs/select.png')}></Image>
                                <Text style={styles.tabText}>生成二维码</Text>
                            </TouchableOpacity>
                            <TouchableOpacity style={styles.tabClick} onPress={this._navigation.bind(this)}>
                                <Image style={styles.tabImg} source={require('../imgs/select.png')}></Image>
                                <Text style={styles.tabText}>一键导航</Text>
                            </TouchableOpacity>
                        </View>
                        <View style={styles.list}>
                            <GridView
                                data={this.state.data}
                                itemsPerRow={2}
                                renderItem={(item, sectionID, rowID, itemIndex, itemID) => {
                                  return (
                                    <Flex
                                      justify="start"
                                      direction="column"
                                      align="start"
                                      style={{flex:1,paddingTop:10,paddingLeft:itemID%2 == 0?0:5,paddingRight:itemID%2 == 0?5:0}}
                                    >
                                        <TouchableOpacity
                                          activeOpacity={1}
                                          style={{backgroundColor:'#FFF',padding:5}}
                                          onPress={() => this._onShowDatail(item)}>
                                              <Image
                                                    source={{uri:`http://www.weiweigo.com${item.imgUrl}`}}
                                                    style={{width:Dimensions.get('window').width/2-25,height:160}}
                                              />
                                              <Text
                                                    numberOfLines={1}
                                                    style={{marginTop:5,color:'#333',fontSize:16}}
                                              >
                                                {item.title}
                                              </Text>
                                              <View style={styles.goodsInfo}>
                                                <Text numberOfLines={1} style={styles.price}>￥{item.price}</Text>
                                                {/*<Text
                                                 style={styles.scanCount}>编号：811215</Text>*/}
                                              </View>
                                              <Text style={styles.remark} numberOfLines={2}>{item.summary}</Text>
                                              {/*<View style={styles.goodsFooter}>
                                                    <TouchableOpacity style={styles.tabGoodsClick} onPress={this._getProErweima.bind(this,item)}>
                                                        <Image style={styles.tabSmallImg} source={require('../imgs/psIcon3.png')}></Image>
                                                        <Text style={styles.tabSmallText}>生成二维码</Text>
                                                    </TouchableOpacity>
                                                    <TouchableOpacity style={styles.tabGoodsClick} onPress={this._share.bind(this)}>
                                                        <Image style={styles.tabSmallImg} source={require('../imgs/psIcon5.png')}></Image>
                                                        <Text style={styles.tabSmallText}>分享推广</Text>
                                                    </TouchableOpacity>
                                              </View>*/}
                                        </TouchableOpacity>
                                    </Flex>
                                  );
                                }}
                            />
                        </View>
                        {
                            this.state.dataSource.getRowCount > 0?
                            <View style={styles.evaluate}>
                                <ListView
                                    dataSource={this.state.dataSource}
                                    renderRow={this._renderRow.bind(this)}
                                    enableEmptySections={true}
                                />
                            </View>
                            : null
                        }

                        <View style={styles.evaInfo}>
                            <Text style={styles.nickLabel}>昵称</Text>
                            <Text style={styles.nickName}>{this.state.username}</Text>
                        </View>
                        <View style={styles.evaView}>
                            <TextInput
                                style={styles.evaInput}
                                placeholder = '请输入评价内容'
                                onChangeText={(value)=>{
                                    this.setState({
                                        comment:value
                                    })
                                }}
                            />
                        </View>
                        <View style={{padding:10}}>
                            <TouchableHighlight
                                style={styles.loginBtn}
                                onPress={this._submit.bind(this)}
                            >
                                <Text style={styles.loginText}>确定发布</Text>
                            </TouchableHighlight>
                        </View>
                    </View>
                </ScrollView>
                <TouchableOpacity style={styles.telphone} onPress={()=>{
                    Communications.phoneCall(this.state.telphone,false)
                }}>
                    <Text style={styles.telnumber}>联</Text>
                    <Text style={styles.telnumber}>系</Text>
                    <Text style={styles.telnumber}>电</Text>
                    <Text style={styles.telnumber}>话</Text>
                </TouchableOpacity>
            </View>
        )
    }

}

const styles = StyleSheet.create({
    container: {
        backgroundColor: '#EEE',
        flex: 1,
        flexDirection:'column'
    },
    sliderImage:{
        width:Dimensions.get('window').width,
        height:100,
    },
    content:{
        flexDirection:'column',
        padding:10
    },
    head:{
        flexDirection:'row',
        alignItems:'center',
        justifyContent:'center'
    },
    title:{
        flex:1,
        fontSize:18,
        color:'#333',
        fontWeight:'600'
    },
    scanCount:{
        fontSize:12,
        color:'#999',
    },
    service:{
        marginTop:10
    },
    serviceDetail:{
        marginTop:3,
        color:'#898989',
        marginBottom:5
    },
    tabIcon:{
        flexDirection:'row',
    },
    tabClick:{
        flexDirection:'row',
        justifyContent:"center",
        alignItems:'center',
        marginLeft:5
    },
    tabGoodsClick:{
        flexDirection:'column',
        alignItems:'center',
        marginLeft:10
    },
    tabImg:{
        width:18,
        height:18
    },
    tabSmallImg:{
        width:25,
        height:25,
        alignSelf:'center'
    },
    tabText:{
        fontSize:12
    },
    tabSmallText:{
        marginTop:5,
        fontSize:13
    },
    list:{
        marginTop:10
    },
    goodsInfo:{
        flexDirection:'row',
        marginTop:3
    },
    price:{
        flex:1,
        fontSize:14,
        color:'#e83828',
    },
    remark:{
        color:'#b1b1b2',
        marginTop:3,
        marginBottom:3,
        paddingRight:5,
        fontSize:13,
        lineHeight:16
    },
    goodsFooter:{
        flexDirection:'row',
        justifyContent:'flex-end',
        marginTop:3
    },
    evaluate:{
        backgroundColor:"#eeeeeF",
        padding:10,
        marginTop:10
    },
    evaluateItem:{
        flexDirection:'row',
        marginTop:10
    },
    evaluateLabel:{
        fontWeight:'600'
    },
    evaluateContent:{
        color:'#999',
        flex:1,
        letterSpacing:0.8,
        marginLeft:3
    },
    evaInfo:{
        flexDirection:'row',
        height:34,
        borderColor:'#CCC',
        borderTopWidth:1/PixelRatio.get(),
        borderBottomWidth:1/PixelRatio.get(),
        alignItems:'center',
        marginTop:20
    },
    nickLabel:{

    },
    nickName:{
        flex:1,
        textAlign:'center'
    },
    evaView:{
        height:120,
        borderColor:'#CCC',
        borderBottomWidth:1/PixelRatio.get(),
    },
    evaInput:{
        flex:1,
        alignItems:'flex-end'
    },
    loginBtn:{
        padding:15,
        backgroundColor:'#FBDC3A',
        marginTop:20,
        borderRadius:3,
        justifyContent:'center',
        alignItems:'center'
    },
    loginText:{
        fontSize:16
    },
    telphone:{
        position:'absolute',
        backgroundColor:'#F00',
        right:15,
        bottom:50,
        padding:5
    },
    telnumber:{
        color:'#FFF',
        marginTop:3
    }
});

export default ProductShops;